<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我发布的需求接单情况</span>
        <el-input
          v-model="orderSearchQuery"
          placeholder="搜索宠物名称"
          clearable
          @clear="handleOrderSearch"
          @keyup.enter.native="handleOrderSearch"
          style="width: 200px; float: right; margin-left: 10px;">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleOrderSearch">
          </el-button>
        </el-input>
      </div>

      <div v-if="ordersLoading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="myOrders.length === 0" class="empty-tip">
        <el-empty description="暂无人接单"></el-empty>
      </div>

      <div v-else>
        <el-table :data="myOrders" stripe>
          <el-table-column prop="petName" label="宠物名称" width="100"></el-table-column>
          <el-table-column prop="acceptorName" label="接单人" width="100"></el-table-column>
          <el-table-column prop="price" label="报价">
            <template slot-scope="scope">
              <span style="color: #ff6b00; font-weight: bold;">￥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="服务时间" width="220">
            <template slot-scope="scope">
              <div>{{ formatDate(scope.row.serviceStartTime) }}</div>
              <div>至</div>
              <div>{{ formatDate(scope.row.serviceEndTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="服务说明" show-overflow-tooltip></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <!-- 待确认状态的接单 -->
              <div v-if="scope.row.status === 'pending'">
                <el-button type="text" style="color: #67C23A;" @click="handleAcceptOffer(scope.row)">同意接单</el-button>
                <el-button type="text" style="color: #F56C6C;" @click="handleRejectOffer(scope.row)">拒绝</el-button>
                <el-button type="text" @click="handlePrivateMessage(scope.row)">私信</el-button>
              </div>
              <!-- 已接受状态的接单 -->
              <div v-else-if="scope.row.status === 'accepted'">
                <el-button type="text" @click="goToTaskNode(scope.row)">查看任务</el-button>
                <el-button type="text" @click="handlePrivateMessage(scope.row)">私信</el-button>
              </div>
              <!-- 已拒绝状态的接单 -->
              <div v-else-if="scope.row.status === 'rejected'">
                <span>已拒绝</span>
                <el-button type="text" @click="handlePrivateMessage(scope.row)">私信</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="orderTotal"
            :page-size="orderPageSize"
            :current-page="orderCurrentPage"
            @current-change="handleOrderPageChange">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 接单详情对话框 -->
    <el-dialog
      title="接单详情"
      :visible.sync="offerDetailDialogVisible"
      width="70%">
      <div v-if="currentOffer" class="offer-detail">
        <el-descriptions title="接单详情" :column="2" border>
          <el-descriptions-item label="接单人">{{ currentOffer.acceptorName }}</el-descriptions-item>
          <el-descriptions-item label="报价">￥{{ currentOffer.price.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="服务开始时间">{{ formatDate(currentOffer.serviceStartTime) }}</el-descriptions-item>
          <el-descriptions-item label="服务结束时间">{{ formatDate(currentOffer.serviceEndTime) }}</el-descriptions-item>
          <el-descriptions-item label="服务说明" :span="2">{{ currentOffer.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="demand-info">
          <h3>需求信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="宠物名称">{{ currentOffer.petName }}</el-descriptions-item>
            <el-descriptions-item label="宠物类型">{{ currentOffer.petType }}</el-descriptions-item>
            <el-descriptions-item label="宠物年龄">{{ currentOffer.petAge }}</el-descriptions-item>
            <el-descriptions-item label="宠物性别">{{ currentOffer.petGender === '0' ? '公' : '母' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="action-buttons" style="margin-top: 20px; text-align: right;">
          <el-button @click="offerDetailDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">拒绝接单</el-button>
          <el-button type="primary" @click="confirmAccept">同意接单</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 私信对话框 -->
    <el-dialog
      title="私信对话"
      :visible.sync="privateMessageDialogVisible"
      width="70%">
      <el-form :model="privateMessageForm" :rules="privateMessageRules" ref="privateMessageForm">
        <el-form-item label="消息内容" prop="message">
          <el-input
            type="textarea"
            v-model="privateMessageForm.message"
            :rows="10"
            placeholder="请输入消息内容"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="privateMessageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendPrivateMessage">发 送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import request from '@/utils/request'

export default {
  name: 'Accept',
  data() {
    return {
      ordersLoading: false,
      myOrders: [],
      orderSearchQuery: '',
      orderTotal: 0,
      orderCurrentPage: 1,
      orderPageSize: 10,
      
      // 接单详情对话框
      offerDetailDialogVisible: false,
      currentOffer: null,
      privateMessageDialogVisible: false,
      privateMessageForm: {
        message: ''
      },
      privateMessageRules: {
        message: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ]
      },
      currentAcceptor: null
    };
  },
  computed: {
    ...mapState({
      userId: state => state.user.id,
      userInfo: state => state.user.info
    })
  },
  created() {
    this.fetchMyOrders();
  },
  methods: {
    fetchMyOrders() {
      this.ordersLoading = true;
      
      request({
        url: `/api/pet-care/offers/my-demands/${this.userId}`,
        method: 'get',
        params: {
          page: this.orderCurrentPage - 1,
          size: this.orderPageSize,
          search: this.orderSearchQuery
        }
      }).then(response => {
        if (response.code === 200) {
          const data = response.data;
          this.myOrders = data.offers;
          this.orderTotal = data.totalItems;
        } else {
          throw new Error(response.msg || '获取数据失败');
        }
        this.ordersLoading = false;
      }).catch(error => {
        console.error('获取接单列表失败:', error);
        this.$message.error('获取接单列表失败，请稍后重试');
        this.ordersLoading = false;
      });
    },
    handleOrderSearch() {
      this.orderCurrentPage = 1;
      this.fetchMyOrders();
    },
    handleOrderPageChange(page) {
      this.orderCurrentPage = page;
      this.fetchMyOrders();
    },
    // 获取状态类型（用于显示不同颜色的标签）
    getStatusType(status) {
      const statusMap = {
        'pending': 'warning',
        'accepted': 'success',
        'rejected': 'info',
        'completed': 'success'
      }
      return statusMap[status] || 'info';
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待确认',
        'accepted': '已接受',
        'rejected': '已拒绝',
        'completed': '已完成'
      }
      return statusMap[status] || '未知状态';
    },
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
    },
    // 处理同意接单
    handleAcceptOffer(row) {
      this.$confirm('确认同意该接单申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.$message({
          message: '正在处理...',
          type: 'info'
        });
        
        // 创建订单数据
        const orderData = {
          publisherId: this.userId,
          acceptorId: row.acceptorId,
          petName: row.petName,
          petType: row.petType,
          serviceType: '寄养',
          startTime: row.serviceStartTime,
          endTime: row.serviceEndTime,
          price: row.price,
          description: row.description
        };
        
        // 先更新报价状态
        request({
          url: `/api/pet-care/offers/${row.id}/status`,
          method: 'put',
          data: {
            status: 'accepted'
          }
        }).then(() => {
          // 创建订单
          return request({
            url: '/api/pet-care/orders',
            method: 'post',
            data: orderData
          });
        }).then(response => {
          if (response.code === 200) {
            this.$message.success('已同意接单，订单已创建');
            this.fetchMyOrders(); // 刷新列表
          } else {
            throw new Error(response.msg || '操作失败');
          }
        }).catch(error => {
          console.error('操作失败:', error);
          this.$message.error('操作失败，请稍后重试');
        });
      }).catch(() => {
        // 取消操作
      });
    },
    // 处理拒绝接单
    handleRejectOffer(row) {
      this.currentOffer = row;
      this.confirmReject();
    },
    // 确认接受
    confirmAccept() {
      this.$confirm('确认同意该接单申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.$message({
          message: '正在处理...',
          type: 'info'
        });
        
        request({
          url: `/api/pet-care/offers/${this.currentOffer.id}/status`,
          method: 'put',
          headers: {
            'Content-Type': 'application/json'
          },
          data: {
            status: 'accepted'
          }
        }).then(response => {
          if (response.code === 200) {
            const index = this.myOrders.findIndex(order => order.id === this.currentOffer.id);
            if (index !== -1) {
              this.myOrders[index].status = 'accepted';
            }
            this.$message.success('已同意接单');
            this.offerDetailDialogVisible = false;
            this.fetchMyOrders(); // 刷新列表
          } else {
            this.$message.error(response.msg || '操作失败');
          }
        }).catch(error => {
          console.error('操作失败:', error);
          this.$message.error('操作失败，请稍后重试');
        });
      }).catch(() => {
        // 取消操作
      });
    },
    // 确认拒绝
    confirmReject() {
      this.$confirm('确认拒绝该接单申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          message: '正在处理...',
          type: 'info'
        });
        
        request({
          url: `/api/pet-care/offers/${this.currentOffer.id}/status`,
          method: 'put',
          headers: {
            'Content-Type': 'application/json'
          },
          data: {
            status: 'rejected'
          }
        }).then(response => {
          if (response.code === 200) {
            const index = this.myOrders.findIndex(order => order.id === this.currentOffer.id);
            if (index !== -1) {
              this.myOrders[index].status = 'rejected';
            }
            this.$message.success('已拒绝接单');
            this.offerDetailDialogVisible = false;
            this.fetchMyOrders(); // 刷新列表
          } else {
            this.$message.error(response.msg || '操作失败');
          }
        }).catch(error => {
          console.error('操作失败:', error);
          this.$message.error('操作失败，请稍后重试');
        });
      }).catch(() => {
        // 取消操作
      });
    },
    // 前往任务节点页面
    goToTaskNode(row) {
      this.$router.push({
        path: '/pet-care/task-node',
        query: { orderId: row.id }
      });
    },
    // 处理私信
    handlePrivateMessage(row) {
      if (!this.userId) {
        this.$message.error('请先登录');
        return;
      }
      
      this.currentAcceptor = {
        id: row.acceptorId,
        name: row.acceptorName
      };
      this.privateMessageDialogVisible = true;
      this.privateMessageForm.message = '';
      this.$nextTick(() => {
        this.$refs.privateMessageForm && this.$refs.privateMessageForm.clearValidate();
      });
    },
    // 发送私信
    sendPrivateMessage() {
      this.$refs.privateMessageForm.validate(valid => {
        if (valid) {
          const message = {
            senderId: this.userId,
            receiverId: this.currentAcceptor.id,
            title: `私信消息`,
            content: this.privateMessageForm.message.trim(),
            type: 'private'
          };

          request({
            url: '/api/message',
            method: 'post',
            data: message
          }).then(() => {
            this.privateMessageDialogVisible = false;
            this.$message({
              message: '私信发送成功',
              type: 'success',
              duration: 2000
            });
            this.privateMessageForm.message = '';
          }).catch(error => {
            console.error('发送私信失败:', error);
            this.$message.error('发送私信失败，请稍后重试');
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.loading-container {
  padding: 20px;
}

.empty-tip {
  padding: 50px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.offer-detail {
  padding: 10px;
}

.demand-info {
  margin-top: 20px;
}

.demand-info h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>
